package com.training.bt.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.training.bt.entity.UserPoint;
import com.training.bt.mapper.UserPointMapper;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class UserPointService {
    private final UserPointMapper userPointMapper;
    private final PointsRecordService pointsRecordService;

    @Transactional
    public void addPoints(Long userId, int points, long size) {
        userPointMapper.update(null,
                new UpdateWrapper<UserPoint>()
                        .setSql("upload_bytes = upload_bytes +" + size)
                        .setSql("point = point +" + points)
                        .eq("user_id", userId));

        pointsRecordService.pointsAdd(userId, points);

    }

    @Transactional
    public UserPoint getUserPoint(Long userId) {
        return userPointMapper.selectById(userId);
    }

    // 实现了添加扣分记录
    @Transactional
    public void deductPoints(Long userId, int points, long size) throws RuntimeException {

        int updated = userPointMapper.deductPoints(userId, points, size);
        if (updated == 0) {
            throw new RuntimeException("积分不足");
        }

        pointsRecordService.pointConsume(userId, points);

    }
}
